require 'kaixin_park'
require 'kaixin_house'
require 'yaml'
require 'miscfunc'
require 'rubygems'
require 'rufus/scheduler'

include MiscFunc

def load_conf(file)
  if not File.exists?(file)
    puts "Please setup the #{file} for configuration first"
    return nil
  else
    @conf = YAML::load_file(file)
  end
end

def process_all(logins)
  # Processing each account
  logins.each do |login|
  
      info "Processing with #{login['email']} .."

      @kaixin.login_to_kaixin_with(login['email'], login['password'].to_s)
      begin
        @kaixin.goto_park
        if login.key?('prefer') || login.key?('nonprefer') then
            prefer = []
            nonprefer = []
            prefer = login['prefer'].to_s.split "|" || []
            nonprefer = login['nonprefer'].to_s.split "|" || []
            @kaixin.reinit_flist(prefer, nonprefer, login["force"])
        end
        # processing parking
        #@kaixin.parking
        if login.key?('post') 
            post_list = login['post'].to_s.split(/ /)
            # process posting
          #  @kaixin.do_post(post_list)
        end
        
        @kaixin.goto_team
        # show all matches' infomation
        @kaixin.show_match
        if login.key?('jy') || login.key?('gg')
          jy_list = login['jy'].to_s.split(/ /) || []
          gg_list = login['gg'].to_s.split(/ /) || []
          # processing oil or gg
         # @kaixin.do_oil(jy_list,gg_list)
        end

        #processing job
        if login.key?('job')
          if (login["job"] == "1")
            @kaixin.goto_joblist
            @kaixin.job
          end
        end
        
        #process 
        if login.key?('stay') && (login['job'] =="1")
          @kaixin.goto_house
          @kaixin.get_verifycode
          homeless_friends = @kaixin.find_homeless_friends
          @kaixin.stay_friends(homeless_friends)
        end
        
        
        # show friends garden's infomation
        # @kaixin.show_friends_garden
      rescue => err
        info err
        next
      end
    sleep 5
    @kaixin.logout
    info "Done!!"
    sleep 5
  end
  # quit
  @kaixin.quit
end

if load_conf("match.yaml")
  
  logins = @conf["logins"]
  
  @kaixin = Kaixin.new
  
  if (schedule = @conf["schedules"])
    if schedule[0].key?('all')
      scheduler = Rufus::Scheduler.start_new
      interval = schedule[0]['all']
      scheduler.every "#{interval}" do
        process_all(logins)
      end    
      scheduler.join
    end    
  end  
  process_all(logins)
else
  exit
end



